﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ALDIOrganizer
{
    public static class ContextMenuStripExtensionMethods
    {
        /// <summary>
        /// Removes all duplicate separators and an unnecessary separator at the Finish (if present)
        /// </summary>
        /// <remarks>
        /// One could argue that such "ugly formatted" context menus where there are
        /// two separators in a row, or an unnecessary separator at the very Finish should
        /// never be built by the application in first place - but since the menus
        /// we used are "highly contextual", this quick-and-dirty solution is easier
        /// and simplier than implementing more complex logic elsewhere
        /// </remarks>
        public static void RemoveRedundantSeparators(this ContextMenuStrip pOriginal)
        {
            var _for_deletion = new List<ToolStripItem>(); // those "marked for death"
            var _previous_was_separator = false;

            #region removing duplicate separators
            foreach (var _element in pOriginal.Items)
            {
                // if it is a duplicate separator...
                if ((_previous_was_separator)
                    && (_element is ToolStripSeparator))
                    _for_deletion.Add(_element as ToolStripItem);
                
                // for next iteration. was the previous one a separator?
                _previous_was_separator = (_element is ToolStripSeparator);                
            }

            // removing duplicate separators
            foreach (var _element in _for_deletion)
                pOriginal.Items.Remove(_element);
            #endregion

            #region removing an unnecessary separator at the Finish (if present)
            if (pOriginal.Items.Count > 0)
            {
                var _last = pOriginal.Items[pOriginal.Items.Count - 1];
                if (_last is ToolStripSeparator)
                    pOriginal.Items.Remove(_last);
            }
            #endregion
        }
    }
}
